
//弹框组件
import { ref, nextTick, Ref, ComponentPublicInstance } from 'vue';
import { Overlay as VanOverlay } from 'vant';
import { h, render, VNode } from 'vue';

// 定义 UseVanPopupOptions 接口
interface UseVanPopupOptions {
    component: any; // 可以是任何 Vue 组件或 JSX 函数
    props?: Record<string, any>;
    onConfirm?: (value: any) => void;
    onCancel?: () => void;
}

// 定义 useVanPopup 返回的对象类型
interface UseVanPopupReturn {
    show: () => void;
    hide: () => void;
}

function useTakePhoto(options: UseVanPopupOptions): UseVanPopupReturn {
    const { component, props = {}, onConfirm, onCancel } = options;
    const container: Ref<HTMLDivElement | null> = ref(null);
    const visible: Ref<boolean> = ref(false);

    function show() {
        if (!container.value) {
            container.value = document.createElement('div');
            document.body.appendChild(container.value);
        }
        visible.value = true;

        if (!component) {
            console.error('Component is undefined or invalid.');
            return;
        }
        const popupVNode: VNode = h(
            VanOverlay,
            { ...props, show: visible.value, onClose: hide },
            {
                default: () =>
                    h(component, {
                        ...props.children,
                        'onUpdate:modelValue': (newValue: any) => {
                            console.log('Model value updated:', newValue);
                        },
                        onConfirm: (value: any) => {
                            handleConfirm(value);
                        },
                        onCancel: () => {
                            handleCancel();
                        },
                    }),
            },
        );

        render(popupVNode, container.value);
    }

    function hide() {
        visible.value = false;
        if (container.value && container.value.parentNode) {
            container.value.parentNode.removeChild(container.value);
            container.value = null;
        }
        // render(null, container.value); // 清空容器内容
    }

    function handleConfirm(value: any) {
        if (onConfirm) {
            onConfirm(value);
        }
        hide();
    }
    function handleCancel() {
        if (onCancel) {
            onCancel();
        }
        hide();
    }

    return {
        show,
        hide,
    };
}

export default useTakePhoto;
